package com.jiecao.news.jiecaonews.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;

import com.google.protobuf.GeneratedMessage;
import com.jiecao.news.jiecaonews.dto.pb.PBAboutArticle.PBArticles;
import com.jiecao.news.jiecaonews.util.constants.Constants;

/**
 * 处理pb对象的工具类
 * @author lidongwei
 *
 */
public class PbUtils {
	
	/**
	 * 从服务端获取pb对象
	 * url为服务器访问地址
	 * clazz为需要转换成的类型
	 * @param url
	 * @param clazz
	 * @return
	 * @throws IOException
	 */
	public static Object downloadPB(String url, Class<?> clazz) throws IOException {
		URL target = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) target.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod("GET");
		conn.setRequestProperty("Content-Type", "application/x-protobuf");
		conn.setRequestProperty("Accept", "application/x-protobuf");
		conn.setRequestProperty("Accept", "application/x-protobuf");
		conn.setConnectTimeout(5000);//设置5秒超时
		// check response code
		int code = conn.getResponseCode();
		System.out.println("code:" + code);
		if(!((code >= 200) && (code < 300))){
			return null;
		}
		InputStream in =  conn.getInputStream() ;
		
		
		Method parseMethod;
		try {
			parseMethod = clazz.getDeclaredMethod("parseFrom", InputStream.class);
		} catch (SecurityException e) {
			e.printStackTrace();
			return null;
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
			return null;
		}
		try {
			GeneratedMessage gm = (GeneratedMessage) parseMethod.invoke(clazz, in);
			in.close();
			return gm;
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			return null;
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			return null;
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 根据条件获取文章列表
	 * @param time 时间节点
	 * @param isAfter 是否在时间节点之后
	 * @param size 文章条数
	 * @param type 文章类型
	 * @param pre 是否为编辑预览
	 * @return PB消息，PBAboutArticle.PBArticles
	 */
	public static PBArticles getPBArticles(String time,String isAfter,Integer size,Integer type,Integer pre ){
		String suffix = "";
		if(null!=time){
			time = time.replaceAll(" ", "%20");
			suffix+="time="+time;
		}
		if(null!=isAfter){
			suffix+="&is_after="+isAfter;
		}
		if(null!=size){
			suffix+="&size="+size;
		}
		if(null!=type){
			suffix+="&type="+type;
		}
		if(null!=pre){
			suffix+="&pre="+pre;
		}
		
		try {
			String url = Constants.ARTICLE_LIST_PRE+"?"+suffix;
			System.out.println(url);
			return (PBArticles)downloadPB(url,PBArticles.class);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

}
